/**
 * Created by JLB1 on 2017/2/7.
 */

import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import Clipboard from 'clipboard';
import AJAX from '../../lib/ajax';
import Tools from '../../lib/tools';
import wx from 'wx';
import Dialog from '../MyPackage/components/Dialog';
import Toast from '../MyPackage/components/Toast';
import AdBlock from '../../components/AdBlock'
import { addErrorListener } from '../../lib/handleError';

import { Auth } from './PickUpDetail.template'

require('../../styles/common.less');
require('../../styles/lux.less');
require('../../styles/resetWeui.less');
require('./PickUpDetail.less');

class ExpressDetail extends Component {
    constructor(props) {
        super(props);
        this.state = {
            order_id: Tools.getParams().order_id,
            aditem_id: Tools.getParams().aditem_id,
            data: {
                id: '',
                type: 1,//1 柜体 2货架 3 堆
                isNeedPay: true,//是否需要支付
                adImgSrc: '',
                out_time: null,
                imgId: '',
                adImggo: 'javascript:;',
                addr: '',
                shareimg: '',
                wait_time: '',
                settle_amount: '',
                basic_amount: '',
                delay_amount: '',
                balance: '',
                exp_code: '',
                exp_name: '',
                open_code: '',
                contact_phone: '',
                contact_desc: '',
                is_agenting: 0,   //是否正在代收中 0否 1是 [新增]      （代收中按钮）
                can_agent: 1,     //是否可代收，0不可以 1可以 [新增]     （找人代收按钮）
                can_pickup: 1,     //是否可取件，0不可以 1可以 [新增]     （一健开箱按钮）
                has_refused_pickup: 0,     //是否拒绝自提
                has_refused_order: 0,     //是否拒收
                logis_id: 0, // 物流中心
                confirmCabinetDialog: false,
                cabinet_code: 0,
                scan_confirm: 0,

                showImg: false,
            },
            //用户位置
            //柜体位置
            isLoading: 1,
            auth_show: null,
            showCostDetail: false,
            taoList: [],
        };
    }

    componentWillMount() {
        addErrorListener()();

        // 取url参数，wx_type
        window.localStorage.setItem('wx_type', Tools.getParams().wx_type === 'garden' ? Tools.getParams().wx_type : 'logis');
        // Tools.createCookie('wx_type', Tools.getParams().wx_type);

        const id = Tools.getParams().order_id;
        const ad_id = Tools.getParams().aditem_id;

        AJAX.request('get_tao_code', {}, data => {
            this.setState({
                taoList: data.body ? data.body.split(',') : [],
            });
        });

        //获取详情
        AJAX.request('order_detail', { order_id: id, aditem_id: ad_id }, data => {
            if (data.code === 0) {
                const dataBody = data.body || {};
                const storage_info = dataBody.storage_info || {};
                const advert = dataBody.advert || {};

                const copyData = {
                    id: dataBody.id,
                    type: storage_info.type,
                    order_type: dataBody.order_type,
                    isNeedPay: dataBody.settle_amount !== 0, //是否需要支付
                    adImgSrc: advert.img,
                    imgId: advert.id,
                    shareimg: dataBody.share_img,
                    adImggo: advert.url,
                    addr: storage_info.addr,
                    wait_time: dataBody.wait_time,
                    out_time: dataBody.out_time,
                    settle_amount: (dataBody.settle_amount / 100).toFixed(2),
                    basic_amount: (dataBody.basic_amount / 100).toFixed(2),
                    delay_amount: (dataBody.delay_amount / 100).toFixed(2),
                    balance: (dataBody.balance / 100).toFixed(2),
                    exp_code: dataBody.exp_code,
                    exp_name: dataBody.exp_name,
                    open_code: dataBody.open_code,
                    contact_phone: dataBody.contact_phone,
                    contact_desc: dataBody.contact_desc,
                    is_agenting: dataBody.is_agenting,   //是否正在代收中 0否 1是 [新增]      （代收中按钮）
                    can_agent: dataBody.can_agent,     //是否可代收，0不可以 1可以 [新增]     （找人代收按钮）
                    can_pickup: dataBody.can_pickup,     //是否可取件，0不可以 1可以 [新增]     （一健开箱按钮）
                    has_refused_pickup: dataBody.has_refused_pickup,     //是否拒绝自提
                    has_refused_order: dataBody.has_refused_order,     //是否拒收
                    logis_id: dataBody.logis_id,    // 物流中心id
                    create_time: dataBody.create_time,
                    in_time: dataBody.in_time,
                    // is_id_authed: dataBody.is_id_authed === 0, // 0:未实名 1:实名通过,  # 用户实名认证状态  (added in 11-20)
                    cabinet_code: dataBody.storage_info.code,
                    scan_confirm: dataBody.storage_info.scan_confirm,
                    pay_amount: dataBody.pay_amount || 0,    //  取件需要支付金额
                    img_url: dataBody.img_url,
                    isStationPickup: dataBody.isStationPickup   // 驿站自主取件开关 1: 开; 2: 关
                };

                this.setState({
                    isLoading: 2,
                    data: copyData,
                    pickup_idcertify_mode: dataBody.pickup_idcertify_mode, // 0禁用/1强制/2非强制,  # 取件实名认证 (added in 11-20)
                    auth_show: dataBody.is_id_authed === 0 && dataBody.pickup_idcertify_mode != 0,
                });
            } else if (data.code === 15101) { // 订单不存在
                this.setState({
                    isLoading: 3,
                });
            }
        });
    }

    componentDidMount() {
        new Clipboard('.right-btn');
        new Clipboard('.icon-copy');
        AJAX.appendBaiduAnalysis();
    }

    //换算为度
    getRad = d => {
        return d * Math.PI / 180.0;//经纬度转换成三角函数中度分表形式。
    }

    // 取件
    handlePickup = () => {
        const { data } = this.state;

        if (data.is_agenting === 1) return;

        if (data.scan_confirm) {
            this.setState({ confirmCabinetDialog: true });
        } else {
            if (data.isNeedPay) {
                window.location.href = './PickUpDetailOne?order_id=' + Tools.getParams().order_id;
            } else {
                Dialog.confirm({
                    title: '',
                    content: '请核对当前地址或柜体编号与取件信息是否一致，否则由此带来的损失由您负责。',
                    okText: '仍要开箱',
                    cancelText: '取消',
                    onOK: () => {
                        window.location.href = `./OpenBoxFinal?order_id=${Tools.getParams().order_id}`
                    },
                })
            }
        }
    }

    //找人代收
    findFriendToPickup = () => {
        const { order_id, aditem_id, is_agenting } = this.state
        if (is_agenting) {
            Dialog.info({
                title: '',
                content: '快递在代收中...',
                okText: '确认',
                cancelText: '取消',
            })
        } else {
            window.location.href = `./ChooseOtherReceiver?order_id=${order_id}&aditem_id=${aditem_id}`
        }
    }

    handleLog = () => {
        const { order_id } = this.state
        window.location.href = './PickUpOrderLog?order_id=' + order_id
    }

    authJump() {
        this.setState({
            auth_show: false,
        })
    }

    authConfirm() {
        window.location.href = './Authentication?src=pick'
    }

    hideConfirmCabinetDialog = () => {
        this.setState({ confirmCabinetDialog: false })
    }

    handleConfirmCabinet = e => {
        e.stopPropagation();

        const { data } = this.state;

        window.location.href = `./ConfirmCabinet?order_id=${data.id}&cabinet_code=${data.cabinet_code}`;
    }

    createConfirmCabinetDialogElem = () => (
        <div
            className="dialog-confirm"
            onClick={this.hideConfirmCabinetDialog}
        >
            <div className="dialog-box">
                <div className="dialog-content">
                    <div className="title">安全提示</div>
                    <div className="desc">为了您的包裹安全，请扫描柜体条码取件</div>
                    <img src="https://cdn2.jinlb.cn/pic/fd/14/fd1414a22495532596caa354efbd510f.png" />
                </div>
                <div
                    className="dialog-footer"
                    onClick={this.handleConfirmCabinet.bind(this)}
                >
                    扫描
                </div>
            </div>
        </div>
    )

    /**
     * 确认取件
     */
    handleSelfHelpPickup = (id, e) => {
        e.stopPropagation();
        const that = this;
        Dialog.confirm({
            title: '提示',
            // content: '请确认是否已取走',
            htmlContent: (<div style={{ padding: '15px' }}>
                <div style={{ color: '#999', marginBottom: '10px' }}>请确认是否已取走</div>
                <div style={{ color: 'red' }}>注意: 确认取走后，该包裹视为本人取走。</div>
            </div>),
            okText: '确认',
            cancelText: '取消',
            onOK: () => {
                // 自助取件
                AJAX.request('fault_pickup', { order_ids: id }, result => {
                    if (!result.body.to_pickup_count || result.body.to_pickup_count < 1) {
                        AJAX.request('get_advert_detail', { type: 6 }, (data) => {
                            if (data.code == 0) {
                                that.fetchSaveAdvert(data.body.id, 4);
                                var advert_url = data.body.url;
                                window.location.href = advert_url;
                            }
                        })
                    } else {
                        const wx_type = window.localStorage.getItem('wx_type');
                        window.location.href = `./PickUp?wx_type=${wx_type}`;   //返回首页
                    }
                });
            },
        })
    }

    /**
     * 
     * @param {*} advertId 广告id
     * @param {*} type 2: 点击; 3: 曝光; 4: 跳转;
     */
    fetchSaveAdvert(advertId, type) {
        const params = {
            advertId: advertId,
            type: type,
        };
        AJAX.request('advertSave', params, (data) => {
            const { code, body } = data;
            if (code === 0) {
                console.log('记录成功', body);
            }
        });
    }

    render() {
        const {
            data,
            isLoading,
            auth_show,
            pickup_idcertify_mode,
            showCostDetail,
            confirmCabinetDialog,
            taoList,
            showImg,
        } = this.state;

        if (isLoading === 1) return null;

        const dataList = [
            { label: '存放位置', value: data.addr },
            { label: '等待时长', value: data.wait_time },
            { label: data.exp_name, value: data.exp_code },
            {
                label: '取件费用', value: data.settle_amount + '元',
                children: [
                    { label: '基础费用', value: data.basic_amount },
                    { label: '延期费用', value: data.delay_amount },
                ],
            },
            { label: '取件密码', value: data.open_code },
            { label: '到校时间', value: data.create_time },
            { label: '投递时间', value: data.in_time },
        ];

        let display_phone = data.contact_phone;
        if (display_phone && display_phone.charAt(0) == 1) {
            display_phone = Tools.formatPhone(display_phone);
        }

        dataList.push({ label: '服务电话', value: display_phone, phone: data.contact_phone.replace('-', '') });
        dataList.push({ label: '面单照片', value: data.img_url });

        if (data.out_time) {
            dataList[1] = {
                label: '取件时间', value: data.out_time,
            };
        }

        const auth_data = {
            show_left: pickup_idcertify_mode === 2, // 实名制非强制会显示左侧的我知道了按钮
            authJump: this.authJump.bind(this),
            authConfirm: this.authConfirm.bind(this),
        }

        let pickupDetail = <div></div>
        if (isLoading === 3) {
            pickupDetail = (
                <div className="expiredPage">
                    <img src="//wechat.jinlb.cn/assets/images/order_expire.png" alt="" />
                </div>
            );
        } else if (isLoading === 2) {
            pickupDetail = (
                <div>
                    <div className="expressDetailBox">
                        {
                            dataList.map((item, index) => (
                                <div>
                                    <div className="lux-d-f lux-ai-c lux-pt10 lux-pb10" style={{ borderBottom: index !== dataList.length - 1 ? '1px solid rgba(238,238,238,1)' : '' }}>
                                        <div className="lux-c999 lux-fz14 lux-fw-500 lux-miw80">{item.label}:</div>
                                        {
                                            index === 2 && (
                                                <div className="lux-flex-1 lux-d-f lux-ai-c">
                                                    <div className="lux-c333 lux-fz14 lux-fw-500">{item.value}</div>
                                                    <img
                                                        className="icon-copy lux-ml20"
                                                        src="https://wechat.jinlb.cn/assets/images/icon-copy.png"
                                                        data-clipboard-text={item.value}
                                                        onClick={() => Toast.success({ content: '复制成功' })}
                                                    />
                                                </div>
                                            )
                                        }
                                        {
                                            item.label === '取件费用' && (
                                                <div className="lux-flex-1 lux-d-f lux-jc-sb">
                                                    <div className="lux-cfe763e lux-fz14 lux-fw-500">{item.value}</div>
                                                    {
                                                        !data.out_time && (
                                                            <div
                                                                className="lux-ca9a9a9 lux-fz14 lux-fw-500"
                                                                onClick={() => this.setState({ showCostDetail: !showCostDetail })}
                                                            >
                                                                {'费用明细 >'}
                                                            </div>
                                                        )
                                                    }
                                                </div>
                                            )
                                        }
                                        {
                                            item.label === '取件密码' && (
                                                <div className="lux-flex-1 lux-d-f lux-jc-sb">
                                                    <div className="lux-cfe763e lux-fz14 lux-fw-500">{item.value}</div>
                                                    {
                                                        data.out_time && (
                                                            <div className="lux-cf16572 lux-fz14 lux-fw-500">
                                                                已无效
                                                            </div>
                                                        )
                                                    }
                                                </div>
                                            )
                                        }

                                        {
                                            item.label === '服务电话' && (
                                                <a href={`tel:${item.phone}`}><div className="lux-cffa600 lux-fz14 lux-fw-500">{item.value}</div></a>
                                            )
                                        }
                                        {
                                            item.label === '面单照片' && (
                                                <div className="lux-cffa600 lux-fz14 lux-fw-500" onClick={() => {
                                                    // this.setState({ showImg: true });
                                                    if (!item.value) return;
                                                    console.log(item.value);
                                                    wx.previewImage({
                                                        current: item.value,
                                                        urls: [item.value],
                                                    });
                                                }}>{item.value ? '查看' : '--'}</div>
                                            )
                                        }

                                        {
                                            index !== 2 && !['取件费用', '取件密码', '服务电话', '面单照片'].includes(item.label) && (
                                                <div className="lux-c333 lux-fz14 lux-fw-500">{item.value}</div>
                                            )
                                        }
                                    </div>
                                    {
                                        showCostDetail && item.children && (
                                            <div className="lux-pt10 lux-pl10 lux-pr10 lux-pb10 lux-bottom-line">
                                                {
                                                    item.children.map(subItem => (
                                                        <div className="lux-flex-1 lux-d-f lux-jc-sb">
                                                            <div className="lux-c999 lux-fz14 lux-fw-500">{subItem.label}</div>
                                                            <div className="lux-cfe763e lux-fz14 lux-fw-500">{subItem.value}</div>
                                                        </div>
                                                    ))
                                                }
                                            </div>
                                        )
                                    }
                                </div>
                            ))
                        }
                    </div>

                    {!data.out_time && <div className="log" onClick={this.handleLog}>订单日志</div>}

                    <AdBlock type="4" />

                    {confirmCabinetDialog && this.createConfirmCabinetDialogElem()}
                </div>
            );
        }

        if (auth_show) {
            pickupDetail = <div><Auth {...auth_data} /></div>
        }

        const sign = Math.floor(Math.random() * taoList.length);




        return (
            <div>
                <div className="lux-pt10 lux-pl10 lux-pr10 lux-pb70">
                    {pickupDetail}
                </div>
                {
                    !auth_show && !data.out_time && (
                        <div className="footer-box">
                            <div className="footer-btn-box" style={{ width: '100%', }}>
                                {
                                    data.type === 1 && (
                                        <button
                                            className={data.is_agenting === 0 ? 'right-btn footer-btn' : 'right-btn footer-btn3'}
                                            onClick={this.handlePickup}
                                            data-clipboard-text={taoList[sign]}
                                        >
                                            {data.is_agenting === 0 ? '一键开箱' : '代收中...'}
                                        </button>
                                    )
                                }
                                {
                                    (data.type !== 1 && data.isStationPickup === 1 && +data.settle_amount === 0) && (
                                        <button className='right-btn footer-btn' onClick={(e) => {
                                            this.handleSelfHelpPickup(data.id, e)
                                        }}>
                                            确认取走
                                        </button>
                                    )
                                }
                                {
                                    (data.type !== 1 && data.settle_amount > 0) && (<div className="contact">
                                        {data.is_agenting === 1 ? '代取中...' : '请到物流中心取件'}
                                    </div>
                                    )
                                }
                            </div>
                        </div>
                    )
                }

                {showImg && <div onClick={() => {
                    this.setState({ showImg: false });
                }} style={{ position: 'fixed', top: '0', left: '0', margin: 0, display: 'flex', backgroundColor: '#0e0e0e', width: '100vw', height: '100vh' }}>
                    <img style={{ display: 'block', margin: 'auto', width: '100%', backgroundColor: 'hsl( 0, 0%, 90%)', transition: 'background-color 300ms' }} src={data.img_url} />
                </div>}
            </div>
        );
    }
}

ReactDOM.render(<ExpressDetail />, document.getElementById('app'));

if (module.hot) {
    module.hot.accept();
}